package cn.wangxl.loglog.web;

import cn.wangxl.loglog.constants.LogTypeEnum;
import cn.wangxl.loglog.service.RocketmqService;
import cn.wangxl.loglog.service.bo.BasicLogBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 日志接受入库web层：
 * 暂时用spring mvc同步方式：
 * 后期需要加入spring mvc异步；
 * 使用netty或vertx进行实现；
 * @Description
 * @Classname LogController
 * @Created by wangxl
 * @Date 2020/5/10 22:34
 */
@Slf4j
@RestController
@RequestMapping("/log")
public class LogController {

    @Autowired
    RocketmqService rocketmqService;

    private ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors()*2,
            1000,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(1000000));

    @PostMapping("/save")
    public String save(@RequestBody BasicLogBO basicLogBO){
        basicLogBO.setCreateTime(LocalDateTime.now());
        System.out.println("异步rocketmq入库");
        // 异步用的太多了，没有必要，增加太多上下文切换，此处实际上可以去掉的
        executorService.submit(()->{
            rocketmqService.saveAsync(basicLogBO,
                    LogTypeEnum.getByType(basicLogBO.getLogType()));
        });
        return "SUCCESS";
    }

    /**
     *
     * @param basicLogBO
     * @return
     */
    @PostMapping("/sync/save")
    public String syncsave(@RequestBody BasicLogBO basicLogBO){
        basicLogBO.setCreateTime(LocalDateTime.now());
        rocketmqService.saveSync(basicLogBO,LogTypeEnum.getByType(basicLogBO.getLogType()));
        return "SUCCESS";
    }

    /**
     *
     * @param basicLogBO
     * @return
     */
    @PostMapping("/async/save")
    public String asyncsave(@RequestBody BasicLogBO basicLogBO){
        basicLogBO.setCreateTime(LocalDateTime.now());
        rocketmqService.saveAsync(basicLogBO,LogTypeEnum.getByType(basicLogBO.getLogType()));
        return "SUCCESS";
    }
}
